package rhc.taskSchedule.taskSchedule.task.execute;

import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import rhc.discribute.node.host.Host;
import rhc.taskSchedule.entity.RunningType;
import rhc.taskSchedule.entity.Task;
import rhc.taskSchedule.entity.TaskType;
import rhc.taskSchedule.exception.TaskException;
import rhc.taskSchedule.exception.TaskTypeException;
import rhc.taskSchedule.taskSchedule.BasicRunning;
import rhc.taskSchedule.taskSchedule.task.TaskExecute;

/**
 * @author lenovo
 *
 */
abstract public class BasicTaskExecuteImpl extends BasicRunning implements TaskExecute {

	/**
	 * 任务id
	 */
	protected String taskId;
	
	protected Task task;
	
	/**
	 * 任务类型
	 */
	protected RunningType runningType=RunningType.TASK;
	
	/**
	 * 任务类型
	 */
	protected TaskType taskType;
	
	public BasicTaskExecuteImpl(String runningId,Host host) throws Exception{
		this.runningId=runningId;
		this.currentHost=host;
		initTask();
	}
	
	/**
	 * 加载任务信息
	 */
	private void initTask() throws Exception{
		initRunning();
		
		taskId=running.getSourceId();
		
		Task task=getTask(taskId);
		this.task=task;
		
		String taskTypeId=task.getTaskTypeId();
		
		TaskType taskType=superDao.getOneT(new Query(Criteria.where(TaskType.COLUMN_ID).is(taskTypeId)), TaskType.class);
		
		if(null == taskType){
			throw new TaskTypeException("任务类型 {} 不存在",taskTypeId);
		}
		
		this.taskType=taskType;
	}
	
	/**根据任务id获取任务
	 * @param taskId
	 * @return
	 */
	protected Task getTask(String taskId) throws Exception{
		Task task=superDao.getOneT(new Query(Criteria.where(Task.COLUMN_ID).is(taskId)), Task.class);
		if(null == task){
			throw new TaskException("任务 {} 不存在",taskId);
		}
		return task;
	}
	
	@Override
	protected RunningType getRunningType(){
		return runningType;
	}

	@Override
	public Task getTask() throws Exception {
		return getTask(taskId);
	}
	
	@Override
	public TaskType getTaskType() throws Exception{
		return taskType;
	}

	@Override
	public String getId() throws Exception {
		return runningId;
	}
	
	@Override
	public String getSourceId() throws Exception {
		return taskId;
	}
}
